package com.example.english.interceptor;

import com.example.english.pojo.Result;
import com.example.english.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheck implements HandlerInterceptor {
    @Override              //目标方法运行前运行
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        //获取请求URL
        String url = req.getRequestURI().toString();
        log.info("请求中的URL:{}", url);

        //判断是否是登录请求，如果包含则放行
        if(url.contains("/login")){
            log.info("登陆操作，放行");
            return true;
        }

        //获取请求头中的令牌（token）
        String jwt = req.getHeader("Authorization");
        log.info("jwt的值为:{}",jwt);
        //判断令牌是否存在
        if(!StringUtils.hasLength(jwt)){
            log.info("请求头为空，返回未登录信息");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }

        //解析令牌
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e){
            //jwt解析失败
            e.printStackTrace();
            log.info("解析令牌失败");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }

        //令牌正确，放行
        log.info("放行");
        return true;

    }

    @Override             //目标方法运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override              //视图渲染完毕后运行，最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
